#include "hal.h"
#include "flash.h"
// 时钟启动停止
void hal_clock_eanble_rch(en_sysctrl_rch_freq_t rch_freq)
{
    ///< RCH时钟不同频率的切换，需要先将时钟切换到RCL
    Sysctrl_SetRCLTrim(SysctrlRclFreq32768);
    Sysctrl_SetRCLStableTime(SysctrlRclStableCycle64);
    Sysctrl_ClkSourceEnable(SysctrlClkRCL, TRUE);
    Sysctrl_SysClkSwitch(SysctrlClkRCL);
    ///< 加载目标频率的RCH的TRIM值
    Sysctrl_SetRCHTrim(rch_freq);
    ///< 使能RCH
    Sysctrl_ClkSourceEnable(SysctrlClkRCH, TRUE);
    ///< 时钟切换到RCH
    Sysctrl_SysClkSwitch(SysctrlClkRCH);
    ///< HCLK不超过24M：此处设置FLASH读等待周期为0 cycle
    Flash_WaitCycle(FlashWaitCycle0);
}
void hal_clock_eanble_xth(void)
{
    en_sysctrl_xth_freq_t sys_xth_freq;
    
    ///< 当使用的时钟源HCLK大于24M：设置FLASH 读等待周期为1 cycle(默认值也为1 cycle)
    if(SYSTEM_XTH > 24000000)
    { 
        // 使能时钟
        Sysctrl_SetPeripheralGate(SysctrlPeripheralFlash, TRUE);
        Flash_WaitCycle(FlashWaitCycle1);    
    }

    if(SYSTEM_XTH < 6000000)
    {
        sys_xth_freq = SysctrlXthFreq4_6MHz;
    }
    if(SYSTEM_XTH < 12000000)
    {
        sys_xth_freq = SysctrlXthFreq6_12MHz;
    }
    if(SYSTEM_XTH < 20000000)
    {
        sys_xth_freq = SysctrlXthFreq12_20MHz;
    }
    if(SYSTEM_XTH < 32000000)
    {
        sys_xth_freq = SysctrlXthFreq20_32MHz;
    }

    Sysctrl_SetXTHFreq(sys_xth_freq);
    Sysctrl_XTHDriverCfg(SysctrlXtalDriver3);
    Sysctrl_SetXTHStableTime(SysctrlXthStableCycle16384);
    Sysctrl_ClkSourceEnable(SysctrlClkXTH, TRUE);
    delay_ms(50);
    Sysctrl_SysClkSwitch(SysctrlClkXTH);
}

void hal_clock_disable_xth()
{
    Sysctrl_ClkSourceEnable(SysctrlClkXTH, FALSE);
}


void hal_clock_eanble_rcl(en_sysctrl_rcl_freq_t rcl_freq)
{
    Sysctrl_SetRCLTrim(rcl_freq);
    Sysctrl_SetRCLStableTime(SysctrlRclStableCycle64);
    Sysctrl_ClkSourceEnable(SysctrlClkRCL, TRUE);
}

void hal_clock_disable_rcl()
{
    Sysctrl_ClkSourceEnable(SysctrlClkRCL, FALSE);
}

void hal_clock_eanble_xtl()
{
    Sysctrl_XTLDriverCfg(SysctrlXtlAmp3, SysctrlXtalDriver3);
    Sysctrl_SetXTLStableTime(SysctrlXtlStableCycle16384);
    Sysctrl_ClkSourceEnable(SysctrlClkXTL, TRUE);
    Flash_WaitCycle(FlashWaitCycle0);    
}

void hal_clock_disable_xtl()
{
    Sysctrl_ClkSourceEnable(SysctrlClkXTL, FALSE);
}
void hal_clock_switch_src(en_sysctrl_clk_source_t src)
{
    Sysctrl_SysClkSwitch(src);
}


